/****************************************************************************

	COPYRIGHT(C) MAXSI SOFTWARE, JONAS 'SORTIE' TERMANSEN 2008, 2009, 2010

    This file is part of Maxsi Installer.

    Maxsi Installer is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Maxsi Installer is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with Maxsi Installer.  If not, see <http://www.gnu.org/licenses/>.

	*/ #include "MaxsiInstallerContributors.h" /*

	If you modify this file, please enter your name below and provide contact
	information in MaxsiEngineContributors.h. For more information please see
	MaxsiEngineContributors.h.
	
	Contributors to this file:

	- Jonas 'Sortie' Termansen
	- [your name here]

	MaxsiInstaller.exe
	The main installing technology utilized in the powerful Maxsi Distribution
	platform.

	PageSteamUsername.cpp
	Which username does the user have?

****************************************************************************/

#include "MaxsiEngine.h"
#include "MaxsiDistributionLink.h"
#include <io.h>
#include "Main.h" 
#include "UI.h" 
#include "Thread.h"
#include "Data.h"

size_t DetectNumGamesInstallForUser( char* Username )
{
	size_t	Result			=	0;

	if ( !InstallPath ) { return 0; }

	char*	SteamAppsPath	=	BuildString(4,InstallPath,"SteamApps/",Username,"/*");

	struct		__finddata64_t File;
	intptr_t	FileHandle;
	bool		HasRequiredGame		=	false;

	if ( (FileHandle = _findfirst64( SteamAppsPath, &File)) != -1L )
	{
		do
		{
			if (File.attrib & _A_SUBDIR)
			{
				Result++;	
			}
			if ( GameFolderReq )
			{
				if ( _stricmp(GameFolderReq,File.name) == 0 )
				{
					HasRequiredGame	=	true;
				}
			}
		}
		while ( _findnext64( FileHandle, &File ) == 0 );

		_findclose( FileHandle );
	}

	if ( HasRequiredGame || GameFolderReq == NULL)
	{
		return Result;
	}
	else
	{
		return 0;
	}
}

List DetectSteamUsername( unsigned int* NameCount, size_t* RecommendedUser )
{
	if ( !NameCount ) { return 0; }
	if ( !InstallPath ) { *NameCount = 0; return 0; }

	char*	SteamAppsPath	=	BuildString(2,InstallPath,"SteamApps/*");

	struct __finddata64_t File;
	intptr_t FileHandle;

	unsigned int	NumNames		=	0;
	unsigned int	NameNum			=	0;
	//char*			SteamUserName	=	0;
	List			NameIndex		=	0;
	size_t			BestUser		=	0;
	size_t			BestScore		=	0;

	for (int K = 0; K<2; K++)
	{
		if ( (FileHandle = _findfirst64( SteamAppsPath, &File)) != -1L )
		{
			do
			{
				if ((File.attrib & _A_SUBDIR)
					&& strcmp(File.name,".") != 0
					&& strcmp(File.name,"..") != 0
					&& strcmp(File.name,"common") != 0
					&& strcmp(File.name,"media") != 0
					&& strcmp(File.name,"SourceMods") != 0
					&& strcmp(File.name,"bugged") != 0	)
				{
					if (K>0)
					{
						NameNum++;
						if ( NameNum > NumNames )
						{
							// If this point is reached, a new folder has been created in the meantime
							// and no space are reserved for it. Just ignore it
						}
						else
						{
							size_t	Score	=	DetectNumGamesInstallForUser(File.name);

							if ( Score > BestScore ) { BestUser = NameNum-1; }

							SetListEntry(NameIndex,NameNum-1,File.name,strlen(File.name)+1);
						}
					}
					else
					{
						// Count the amount of possible Usernames
						NumNames++;
					}
				}
			}
			while ( _findnext64( FileHandle, &File ) == 0 );

			if ( K == 0 )
			{
				NameIndex = CreateList(NumNames+1);
			}

		}
		_findclose( FileHandle );
	}

	memcpy(NameCount,&NumNames,sizeof(NumNames));
	memcpy(RecommendedUser,&BestUser,sizeof(BestUser));

	delete[] SteamAppsPath;

	return NameIndex;
}

bool PageSteamUsername::InitializeForm(ME_Window* Parent)
{
			NumNames			=	0;
			ControlList			=	0;
	size_t	RecommendedUser		=	0;

	BaseClass::InitializeForm(Parent);

	SteamUserNameList = DetectSteamUsername(&NumNames,&RecommendedUser);

	RECT ClientSpace;
	GetClientRect (WindowHWND, &ClientSpace);

	Previous	=	CreateButton(WindowHWND,_MESTR("Previous"),0,0,0,0);
	Next		=	CreateButton(WindowHWND,_MESTR("Next"),0,0,0,0);

	char*	TextSTR;
	
	if ( NumNames > 0 )
	{
		ControlList			=	new HWND[NumNames];
		bool	Selected	=	false;

		for (unsigned int I = 0; I < NumNames; I++)
		{
			if (SteamUserName)
			{
				Selected =	_stricmp((const char*)GetListEntry(SteamUserNameList,I),SteamUserName) == 0;
			}
			else
			{
				Selected = (I==RecommendedUser);
			}
			ControlList[I] = CreateRadioButtonA(WindowHWND,(char*)GetListEntry(SteamUserNameList,I),25+100*(I-(I%6))/6,100+24*(I%6),100,24,Selected);
		}
	}
	else
	{
		SteamUserNameText = CreateTextA(WindowHWND,SteamUserName,0,0,0,0);


	}
	TextSTR = BuildString(1,
	"Please write your Steam Username below, "
	"the Maxsi Distribution Content Serves require it in order to register your copy. This username will never be published.")
	;

	Text		=	CreateLabelA(WindowHWND,TextSTR,0,0,0,0);
	delete[] TextSTR;

	NewResolution((WORD)ClientSpace.right,(WORD)ClientSpace.bottom);


	return true;
}

bool PageSteamUsername::RenderForm(HWND hWnd)
{
	return	BaseClass::RenderForm(hWnd);
}

LRESULT PageSteamUsername::WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	if (!Initialized) { return 0; }

	if ( message == WM_COMMAND )
	{
        switch(LOWORD(wParam)) 
        {
            case BN_CLICKED:
			{
				HWND ClickedButton = (HWND)lParam;
				if (NumNames == 0 &&(ClickedButton == Previous||ClickedButton == Next))
				{
					if ( SendMessageA(SteamUserNameText,EM_LINELENGTH,(WPARAM) 0,(LPARAM) 0) == 0)
					{
						MessageBoxA(hWnd,"Please write your Steam Username in the Text Box.",ProductName,MB_ICONINFORMATION);
						break;
					}						
				}
				if (ClickedButton == Previous)
				{
					ReplaceSelfWith( (MaxsiUI_Form*) new PageWhereToInstall );
				}
				else if (ClickedButton == Next)
				{
					ReplaceSelfWith( (MaxsiUI_Form*) new PageRevise );
				}
			}				
            break;
			default:
			{
				return BaseClass::WindowProc(hWnd,message,wParam,lParam);
			}
		}
	}
	else
	{
		return BaseClass::WindowProc(hWnd,message,wParam,lParam);
	}
    return (0);

}


bool PageSteamUsername::TerminateForm()
{
	// Avoid calling this function twice, or worse,
	// if one of the functions called here invokes another
	// windows message that eventually leads to this point of code again.
	if (!Initialized) { return false; }
	Initialized	=	false;



	LRESULT Checked = 0;

	if ( NumNames > 0 )
	{
		for (unsigned int I = 0; I < NumNames; I++)
		{
			Checked = SendMessage(ControlList[I],BM_GETCHECK,0,0);

			if (Checked == BST_CHECKED)
			{
				if ( SteamUserName ) { delete[] SteamUserName; }
				SteamUserName	=	BuildString(1,GetListEntry(SteamUserNameList,I));

			}
			DestroyWindow(ControlList[I]);
		}
	
		delete[] ControlList;
	}
	else
	{
		WORD SteamUserName_Len = (WORD)SendMessageA(SteamUserNameText,EM_LINELENGTH,(WPARAM) 0,(LPARAM) 0);
		SteamUserName = new char[SteamUserName_Len+1];
		memset(SteamUserName,0,(size_t)SteamUserName_Len+1);
		memcpy(SteamUserName,&SteamUserName_Len,sizeof(SteamUserName_Len));

		SendMessageA(SteamUserNameText,EM_GETLINE,(WPARAM)0,(LPARAM)SteamUserName);
		DestroyWindow(SteamUserNameText);
	}

	DeleteList(SteamUserNameList);

	DestroyWindow(Previous);
	DestroyWindow(Next);
	DestroyWindow(Text);

	// If we are here, we are safe. Call the parent and ask him to continue our work.
	// Make sure he sets Initialized to false afterwards.
	Initialized	=	true;
	BaseClass::TerminateForm();
	return true;
}

bool PageSteamUsername::NewResolution( WORD Width, WORD Height)
{
	BaseClass::NewResolution(Width,Height);

	// Move the window, validate the Window, redraw the window	
	MoveWindow(Previous,Width-2*125,Height-2*24,100,24,TRUE);
	MoveWindow(Next,Width-1*125,Height-2*24,100,24,TRUE);
	MoveWindow(Text,25,60,Width-25-25,100-60,TRUE);
	if ( SteamUserNameText )
	{
		MoveWindow(SteamUserNameText,25,110,Width-25-25,24,TRUE);
	}
	else
	{
		for (unsigned int I = 0; I < NumNames; I++)
		{
			HWND RadioButton = *(HWND*)ControlList+I*sizeof(RadioButton);
			if ( RadioButton )
			{
				MoveWindow(RadioButton,25+100*(I-(I%6))/6,100+24*(I%6),100,24,TRUE);
			}
		}
	}

	return true;
}